package com.stockz.ui.swing.charting.view;

import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JPanel;

import org.springframework.util.StringUtils;

import com.stockz.ui.swing.charting.decorator.StockChartPanelLayoutDecorator;
import com.stockz.ui.swing.charting.painter.StockChartPanelPainter;
import com.stockz.ui.swing.charting.util.RefreshChartingDataUtil;
import com.stockz.ui.swing.charting.util.SetStockChartViewPortUtil;

public class StockChartPanel extends JPanel{
	private static final long serialVersionUID = 3723244455190418620L;
	
	private static boolean firstTimePaint = true;
	
	private final StockChartPanelState stockChartPanelState;
	private final StockChartPanelSkin stockChartPanelSkin;
	private final StockChartPanelStructure stockChartPanelStructure;
	private StockChartView view;
	
	public StockChartPanel(StockChartView view){
		this.stockChartPanelState = new StockChartPanelState(this);;
		this.stockChartPanelSkin = new StockChartPanelSkin(this);
		this.stockChartPanelStructure = new StockChartPanelStructure(this);
		this.view = view;
		setFocusable(true);
		setBorder(null);
		setFont(getStockChartPanelSkin().getMediumFont());
		setBackground(getStockChartPanelSkin().getBackgroundColor());
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		/*Display first scrip in the list if no scrip is selected*/
		if(stockChartPanelState.getScrip() == null
				&& view.getScripList() != null
				&& !view.getScripList().isEmpty()){
			stockChartPanelState.setScrip(view.getScripList().get(0));
			RefreshChartingDataUtil.refreshChartingData(this);
		}
		
		StockChartPanelLayoutDecorator.decorate(this);
		StockChartPanelPainter.paint((Graphics2D)g, this, getVisibleRect());
		if(firstTimePaint){
			if(stockChartPanelState.getScrip() != null
					&& StringUtils.hasText(stockChartPanelState.getScrip().getName())){
				view.setTitle(stockChartPanelState.getScrip().getName());
			}
			SetStockChartViewPortUtil.setStockChartViewPort(this);
			firstTimePaint = false;
		}
	}

	public StockChartPanelSkin getStockChartPanelSkin() {
		return stockChartPanelSkin;
	}

	public StockChartPanelStructure getStockChartPanelStructure() {
		return stockChartPanelStructure;
	}

	public StockChartPanelState getStockChartPanelState() {
		return stockChartPanelState;
	}

	public StockChartView getView() {
		return view;
	}

	public void setView(StockChartView view) {
		this.view = view;
	}
}
